import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, message } from 'antd';
import type { SorterResult } from 'antd/es/table/interface';
import React, { useRef, useState } from 'react';
import type { AddItem, SysDictItem, SysDictItemUpdate, TableListItem } from './data';
import { addSysDict, getSysDict, queryAllSysDictValue, updateSysDict } from './service';
import EditForm from './components/EditForm';
import type { ResponseData } from '@/utils/request';
import { PlusOutlined } from '@ant-design/icons';
import AddForm from '@/pages/System/DictCode/components/AddForm';

const TableList: React.FC<{}> = () => {
  const [sorter, setSorter] = useState<string>('');

  const [addVisible, setAddVisible] = useState<boolean>(false);

  const [editModalVisible, handleEditModalVisible] = useState<boolean>(false);
  const [detailItemId, setDetailItemId] = useState<string | null>(null);
  const actionRef = useRef<ActionType>();

  async function addHandler(fields: AddItem) {
    const hide = message.loading('正在修改');
    try {
      const response: ResponseData<SysDictItem> = await addSysDict(fields);
      hide();
      if (response.code === 0) {
        message.success('新增成功');
        // eslint-disable-next-line no-unused-expressions
        actionRef.current?.reload();
      } else {
        message.success(response.message);
      }
      handleEditModalVisible(false);
      return true;
    } catch (error) {
      hide();
      message.error('新增失败请重试！');
      handleEditModalVisible(false);
      return false;
    }
  }

  async function handleEdit(fields: SysDictItemUpdate) {
    const hide = message.loading('正在修改');
    try {
      const response: ResponseData<SysDictItem> = await updateSysDict(fields);
      hide();
      if (response.code === 0) {
        message.success('修改成功');
        // eslint-disable-next-line no-unused-expressions
        actionRef.current?.reload();
      } else {
        message.success(response.message);
      }
      handleEditModalVisible(false);
      return true;
    } catch (error) {
      hide();
      message.error('修改失败请重试！');
      handleEditModalVisible(false);
      return false;
    }
  }

  // @ts-ignore
  const columns: ProColumns<TableListItem>[] = [
    {
      title: '字典说明',
            dataIndex: 'dataDesc',
      hideInSearch: true,
    },
    {
      title: '字典编码',
            dataIndex: 'dataCode',
      hideInSearch: true,
    },
    {
      title: '字典值',
            dataIndex: 'dataValue',
      hideInSearch: true,
    },
    {
      title: '字典排序',
            dataIndex: 'sortNo',
      hideInSearch: true,
    },
    {
      title: '操作',
            dataIndex: 'options',
      hideInSearch: true,
      render: (_, record) => {
        const onClickDetail = () => {
          handleEditModalVisible(true);
          setDetailItemId(record.id);
        };
        if (record.changeable) {
          return (
            <div>
              <a onClick={onClickDetail}>设置</a>
            </div>
          );
        }
        return <div />;
      },
    },
  ];

  return (
    <PageHeaderWrapper>
      <ProTable<TableListItem>
        headerTitle="字典设置"
        actionRef={actionRef}
        rowKey="id"
        onChange={(_, _filter, _sorter) => {
          const sorterResult = _sorter as SorterResult<TableListItem>;
          if (sorterResult.field) {
            setSorter(`${sorterResult.field}_${sorterResult.order}`);
          }
        }}
        scroll={{ x: true }}
        params={{
          sorter,
        }}
        toolBarRender={() => [
          <Button type="primary" onClick={() => setAddVisible(true)}>
            <PlusOutlined /> 添加
          </Button>,
        ]}
        tableAlertRender={() => false}
        request={(params = {}) => {
          const { current: page, pageSize, ...filter } = params;
          return queryAllSysDictValue({ page, pageSize, ...filter });
        }}
        columns={columns}
        rowSelection={false}
      />

      <AddForm
        modalVisible={addVisible}
        onSubmit={addHandler}
        onCancel={(visible) => setAddVisible(visible || false)}
      />

      {editModalVisible && detailItemId && (
        <EditForm
          dictId={detailItemId}
          modalVisible={editModalVisible}
          onSubmit={(value: SysDictItemUpdate) => handleEdit(value)}
          onCancel={() => handleEditModalVisible(false)}
          request={async (id: string): Promise<{ success: boolean; data: SysDictItem | null }> => {
            const data = await getSysDict({ id });
            if (data) {
              return { success: true, data: data.data };
            }
            return { success: false, data: null };
          }}
        />
      )}
    </PageHeaderWrapper>
  );
};

export default TableList;
